package com.fingard.dsp.bank.directbank.cmbunion02;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.directbank.cmbunion02.utils.SignatureUtil;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.*;
import com.fingard.text.StringHelper;

import java.util.HashMap;
import java.util.Map;

public class CMBUnion02JSAPIOrder extends CMB02UnifiedOrder implements IJSAPIOrder {
    @Override
    public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
        RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        retAts.rdSeq = p_req.rdSeq;
        try{
            ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "");
            if (actItem != null) {
                Map<String, String> requestPublicParams = getCommonMap();
                Map<String, Object> order = new HashMap<String, Object>();
                order.put("merId", actItem.merchantId);
                order.put("subAppId", actItem.appIdMap.get("JSAPI"));
                order.put("tradeType", "JSAPI");
                order.put("tradeScene", "INSURANCE");
                order.put("orderId", p_req.rdSeq);
                order.put("userId", actItem.userCode);
                order.put("body", p_req.description);
                order.put("mchReserved", p_req.attach);
                if (StringHelper.hasAnyChar(p_req.timeExpire)) {
                    order.put("payValidTime", changeToMIn(p_req));
                }
                order.put("notifyUrl", actItem.notifyURL);
                order.put("txnAmt", changeCurToFen(p_req.amount));
                order.put("currencyCode", "156");
                order.put("spbillCreateIp", actItem.createIP);
                boolean limit = getBankConfig().getValueAsBool("limitPay");
                WriteBankUrlLogLn("招商聚合能否用信用卡支付："+limit);
                if(!limit){
                    order.put("limitPay", "no_credit");
                }
                if (StringHelper.hasAnyChar(p_req.openid)) {
                    order.put("subOpenId", p_req.openid);// 用户ID
                }else{
                    if (StringHelper.isNullOrEmpty(p_req.code)) {
                        retAts.respCode = "-1";
                        retAts.respInfo = "Code和Openid不能同时为空";

                        return retAts;
                    } else {
                        if (StringHelper.isNullOrEmpty(actItem.appSecret)) {
                            retAts.respCode = "-1";
                            retAts.respInfo = "未配置公众号的appsecret";

                            return retAts;
                        } else {
                            HashMap<String, String> hashOpenid = getOpenid(actItem.appIdMap.get("JSAPI"), actItem.appSecretMap.get("JSAPI"), p_req.code);

                            if (hashOpenid.get("RespCode").equals("0")) {
                                if (hashOpenid.containsKey("openid")) {
                                    order.put("subOpenId", hashOpenid.get("openid"));
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.payInfoCode = FailCode.E9981;

                                    String errcode = "";
                                    if (hashOpenid.containsKey("errcode")) {
                                        errcode = hashOpenid.get("errcode");
                                    }

                                    String errmsg = "";
                                    if (hashOpenid.containsKey("errmsg")) {
                                        errmsg = hashOpenid.get("errmsg");
                                    }

                                    retAts.respInfo = StringHelper.joinNotEmpty("-", errcode, errmsg);
                                    retAts.transState = PaymentState.FAIL_Payment;

                                    return retAts;
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = hashOpenid.get("RespInfo");

                                return retAts;
                            }
                        }
                    }
                }
                JSONObject identity = new JSONObject();
                identity.put("need_check","T");
                identity.put("name", p_req.oppActName);
                identity.put("mobile", p_req.cellPhone);
                identity.put("type", "IDCARD");
                identity.put("number", p_req.certNumber);
                order.put("identity", identity.toJSONString());
                WriteBankUrlLogLn("招商聚合扫码下单地址："+bankFront.serverURL+"/onlinepay");
                ObjectMapper mapper = new ObjectMapper();
                requestPublicParams.put("biz_content", mapper.writeValueAsString(order));
                WriteBankLogLn("招商聚合加签前的报文内容：" + mapper.writeValueAsString(requestPublicParams));
                String signContent= SignatureUtil.getSignContent(requestPublicParams);
                String sign = SignatureUtil.rsaSign(signContent, actItem.ownKeyStorePath, "UTF-8");
                requestPublicParams.put("sign", sign);
                String[] tmpStrRet = sendToBank(sign,mapper.writeValueAsString(requestPublicParams),bankFront.serverURL+"/onlinepay",actItem);
                if(tmpStrRet[0].length() == 0){
                    JSONObject resultObj = JSONObject.parseObject(tmpStrRet[1]);
                    if(resultObj.get("returnCode")!=null && "SUCCESS".equals(resultObj.get("returnCode"))){
                        JSONObject biz_content = JSONObject.parseObject(resultObj.getString("biz_content"));
                        if(resultObj.get("respCode")!=null && "SUCCESS".equals(resultObj.get("respCode"))){
                            JSONObject bizContent = JSONObject.parseObject(resultObj.getString("biz_content"));
                            JSONObject payData = bizContent.getJSONObject("payData");
                            retAts.respCode = "0";
                            retAts.respInfo = "请求成功";
                            retAts.customHashMap = new HashMap<String, String>();
                            retAts.customHashMap.put("appId", payData.getString("appId"));
                            retAts.customHashMap.put("nonceStr", payData.getString("nonceStr"));
                            retAts.customHashMap.put("timeStamp", payData.getString("timeStamp"));
                            retAts.customHashMap.put("package",	payData.getString("package"));
                            retAts.customHashMap.put("signType", payData.getString("signType"));
                            retAts.customHashMap.put("paySign",	payData.getString("paySign"));
                            retAts.outTransID = biz_content.getString("cmbOrderId");
                        }else {
                            retAts.respCode = "-1";
                            retAts.respInfo = resultObj.getString("respMsg");
                        }
                    }else {
                        retAts.respCode = "-1";
                        retAts.respInfo = resultObj.getString("respMsg");
                    }
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        return retAts;
    }

    @Override
    public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
        return queryUnifiedOrder(p_req);
    }

    @Override
    public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
        return null;
    }
}
